package cn.stronglink.suite.core.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

import cn.stronglink.suite.core.support.Assert;

/**
 * 条形码生成工具类 
 * 
 * @author lei_w
 *
 */
public class BarCodeUtil {
	
	private static int WIDTH = 400;
	
	private static int HEIGHT = 60;

	public static final String strToBase64(String code) {
		return strToBase64(code, WIDTH, HEIGHT);
	}
	
	public static final String strToBase64(String code, int width, int height) {
		Assert.notNull(code, "CODE");
	        
		ByteArrayOutputStream bos = null;  
		  
        MultiFormatWriter formatWriter = new MultiFormatWriter();  
 
        try{  
            BitMatrix bitMatrix = formatWriter  
                    .encode(code, BarcodeFormat.CODE_39, width, height, null);  
            
            bos = new ByteArrayOutputStream();

            MatrixToImageWriter.writeToStream(bitMatrix, "jpg", bos); 
  
            String img = StringUtils.deleteWhitespace(Base64.encodeBase64String(bos.toByteArray()));  
            return String.format("data:image/png;base64,%s", img);  
        } catch (Exception e){  
            throw new RuntimeException(e);  
        } finally{  
            if (bos != null){  
                try{  
                    bos.close();  
				} catch (IOException e){  
                }  
            }  
        }  
	}
	
	public static void main(String[] args){
		String sss = BarCodeUtil.strToBase64("LSVFA49J232037048", 20, 20);
		System.out.println(sss);
	}
}
